﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text.RegularExpressions;
using System.Linq.Expressions;

namespace TestOnlineProject.Common
{
    public static class CustomHtmlHelper
    {
        /// <summary>
        /// Truncate string.
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="text"></param>
        /// <param name="length"></param>
        /// <returns></returns>

        public static MvcHtmlString Truncate(this HtmlHelper helper, string text, int length)
        {
            if (text.Length > length)
            {
                return new MvcHtmlString(text.Substring(0, length) + "...");
            }
            return new MvcHtmlString(text);
        }

        //public static MvcHtmlString ReplaceHtml(this HtmlHelper helper, string text, string pattern, string replacement)
        //{
        //    return new MvcHtmlString(Regex.Replace(helper.Encode(text), pattern, replacement));
        //    //return helper.Raw(helper.Encode(text).Replace(pattern, replacement));
        //}

        /// <summary>
        /// Display With Breaks For field.
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="html"></param>
        /// <param name="expression"></param>
        /// <returns></returns>

        public static MvcHtmlString DisplayWithBreaksFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
        {
            var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            var model = html.Encode(metadata.Model).Replace("\r\n", "<br />\r\n").Replace("<", "&lt").Replace(">", "&gt");

            if (String.IsNullOrEmpty(model))
                return MvcHtmlString.Empty;

            return MvcHtmlString.Create(model);
        }

        //public static IHtmlString ReplaceBreaks(this HtmlHelper helper, string str)
        //{
        //    return MvcHtmlString.Create(str);
        //}
    }
}